<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="授课学校" prop="deptName">
            <!-- <el-tree-select
              v-model="queryParams.deptName"
              clearable
              filterable
              :data="deptOptions"
              :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
              value-key="deptId"
              placeholder="请选择学校"
              :render-after-expand="false"
            /> -->
            <el-select v-model="queryParams.deptName" placeholder="请选择学校" clearable>
              <el-option v-for="item in tenantOptions" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学科" prop="testSubject">
            <el-select v-model="queryParams.testSubject" clearable placeholder="请选择学科">
              <el-option v-for="dict in subjectOptions" :key="dict.id" :label="dict.subjectName" :value="dict.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="授课时间" prop="testDate">
            <el-date-picker
              clearable
              v-model="queryParams.testDate"
              type="date"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择授课时间"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="primary" @click="handleAdd" v-hasPermi="['core:testTeachSchedule:add']">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <h2>实验排课</h2>
      </template>
      <!-- 日历表 -->
      <div class="table-header">
        <el-tag type="info">
          {{ currentWeekRange[0] + '至' + currentWeekRange[1] }}
        </el-tag>
        <div class="center">
          <el-button @click="weekPre"> <i class="el-icon-arrow-left"></i>上一周 </el-button>
          <p>{{ currentYear }}年{{ currentMonth }}月</p>
          <el-button @click="weekNext"> 下一周<i class="el-icon-arrow-right"></i> </el-button>
        </div>
      </div>
      <el-card shadow="never">
        <!-- 表标题 -->
        <table align="center" cellpadding="0" cellspacing="0">
          <tr class="special">
            <td>
              <el-icon :size="20" @click="dialogVisible = true" style="cursor: pointer; margin-bottom: 20px"><Calendar /></el-icon>
            </td>
            <!-- 周 -->
            <td v-for="(item, index) in weekGround" :key="index" class="special-cell">
              {{ item }}
            </td>
          </tr>

          <tr v-for="(item, index) in timeGround" :key="index">
            <!-- 课程时间轴 -->
            <td class="time">{{ index + 1 }}</td>
            <!-- 第几周 -->
            <td align="center" valign="middle" v-for="(dayCourses, index1) in course" :key="index1">
              <!-- 检查当天是否有课程 -->
              <div v-if="dayCourses.length > 0">
                <!-- 遍历当天的所有课程 -->
                <div
                  class="course-item"
                  v-for="(courseItem, index2) in dayCourses"
                  :key="index2"
                  @click="handleView(courseItem)"
                  :style="{ backgroundColor:coachColorMap[courseItem.subjectName]? hexToRgba(coachColorMap[courseItem.subjectName], 0.4) : hexToRgba(colorList[index2], 0.4)}"

                >
                  <!-- <p :style="{ color: coachColorMap[courseItem.subjectName] }"> -->
                  <p :style="{ color: coachColorMap[courseItem.subjectName] ? hexToRgba(coachColorMap[courseItem.subjectName], 0.4) :hexToRgba(colorList[index2]) }">
                    {{ getSubjectNameById(subjectOptions, courseItem.testSubject) }}
                  </p>
                </div>
              </div>
              <!-- 如果当天没有任何课程，则显示 "+" 号 -->
              <div v-else class="course-item" @click="handleAdd">+</div>
            </td>
          </tr>
        </table>
      </el-card>
      <el-dialog v-model="dialogVisible" title="选择日期">
        <el-date-picker v-model="queryParams.testDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择授课时间" />
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addCourse">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <!--  -->
    </el-card>

  </div>
</template>

<script setup name="TestTeachSchedule" lang="ts">
import {
  listTestTeachScheduleCard,
  listTestTeachSchedule,
  getTestTeachSchedule,
  delTestTeachSchedule,
  addTestTeachSchedule,
  updateTestTeachSchedule
} from '@/api/core/testTeachSchedule';
import { TestTeachScheduleVO, TestTeachScheduleQuery, TestTeachScheduleForm } from '@/api/core/testTeachSchedule/types';
import { formatDate as format } from '@/utils/index';
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_notice_type, sys_period } = toRefs<any>(proxy?.useDict('sys_notice_type', 'sys_period'));

// 学校
import { getSubjectNameById,getTeacherNameById } from '@/utils/index';
import { useSchoolList,useTenantlList } from '@/composables/useSchoolList';
const { deptOptions, fetchSchoolList } = useSchoolList();
//学校改租户数据
const { tenantOptions, fetchTenantlList} = useTenantlList();
//学科
import { useSubjectList } from '@/composables/useSubjectList';
const { subjectOptions, fetchSubjectList } = useSubjectList();

const testTeachScheduleList = ref<TestTeachScheduleVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const testTeachScheduleFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: TestTeachScheduleForm = {
  testName: undefined,
  testPeriod: undefined,
  testGrade: undefined,
  testClass: undefined,
  testSubject: undefined,
  testTeacher: undefined,
  testRoot: undefined,
  testDate: undefined
};
const data = reactive<PageData<TestTeachScheduleForm, TestTeachScheduleQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    testName: undefined,
    testPeriod: undefined,
    testGrade: undefined,
    testClass: undefined,
    testSubject: undefined,
    testTeacher: undefined,
    testRoot: undefined,
    testDate: undefined,
    params: {}
  },
  rules: {
    testName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
    testPeriod: [{ required: true, message: '学段不能为空', trigger: 'blur' }],
    testGrade: [{ required: true, message: '年级不能为空', trigger: 'blur' }],
    testClass: [{ required: true, message: '班级不能为空', trigger: 'blur' }],
    testSubject: [{ required: true, message: '学科不能为空', trigger: 'blur' }],
    testTeacher: [{ required: true, message: '授课老师不能为空', trigger: 'blur' }],
    testRoot: [{ required: true, message: '授课教室不能为空', trigger: 'blur' }],
    testDate: [{ required: true, message: '授课时间不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
/** 日历规则 */
// 定义课程接口
interface Course {
  id: number;
  courseId: number;
  courseName: string;
  coursePeriod: string;
  courseGrade: string;
  courseSubject: number;
  courseArea: number;
  courseDate: string;
  courseDateEnd: string;
  courseDept: number;
  deptName: string;
  subjectName: string;
  coach: string;
  title: string;
  testSubject: string,
}

// 初始化数据
const weekGround = ref(['周一', '周二', '周三', '周四', '周五', '周六', '周日']);
const course = ref<Array<Array<Course>>>([]);
const dialogVisible = ref(false);
const currentYear = ref(0);
const currentMonth = ref(0);
const Now = ref(0);
const currentWeek = ref(0);
const days = ref<Date[]>([]);
const currentWeekRange = ref<string[]>([]);
const coachColorMap = reactive<{ [key: string]: string }>({
  英语: '#5974c0',
  数学: '#521262',
  语文: '#20822a'
});

const coachColorMap1 = ref({
  CoachA: '#ff0000', // 红色
  CoachB: '#00ff00', // 绿色
  CoachC: '#0000ff', // 蓝色
});
const colorList = ref([
  '#5974c0',
  '#521262',
  '#20822a',
  "#b8d38f",//马卡龙抹茶奶霜
  "#ddff95",//开心果杏仁饼
  "#f1f1b8",//杏仁饼黄
  "#f1ccb8",//杏仁饼橙
  "#b8f1cc",//杏仁饼绿
  "#b8f1ed",//杏仁饼海洋蓝
  "#e7dbca",//马卡龙枫武
  "#f1b8f1",//马卡龙粉
  "#d9b8f1",//杏仁饼紫
  "#f1ccb8",//盐焦仁糖杏饼
  "#cb8e85",//巧克力马卡龙
  "#fd803a",//马卡龙玫瑰果
])
const courseItem = ref({ coach: 'CoachA' }); // 示例课程项

// 方法：将十六进制颜色值转换为带有透明度的 rgba 值
const hexToRgba = (hex, opacity) => {
  hex = hex.replace('#', '');
  const r = parseInt(hex.substring(0, 2), 16);
  const g = parseInt(hex.substring(2, 4), 16);
  const b = parseInt(hex.substring(4, 6), 16);
  return `rgba(${r}, ${g}, ${b}, ${opacity})`;
};
// 日历选择
const addCourse = () => {
  updateDateAndFetchList(queryParams.value.testDate);
  // 关闭对话框
  dialogVisible.value = false;
};
// 计算每天的最大课程数
const maxCourseLength = computed(() => {
  return Math.max(...course.value.map((day) => day.length));
});
const formatDate = (year: number, month: number, day: number) => {
  const y = year;
  let m = month < 10 ? `0${month}` : month;
  let d = day < 10 ? `0${day}` : day;
  return `${y}-${m}-${d}`;
};

const initData = (cur?: Date) => {
  const date = cur ? new Date(cur) : new Date();
  Now.value = date.getDate();
  currentYear.value = date.getFullYear();
  currentMonth.value = date.getMonth() + 1;
  currentWeek.value = date.getDay();
  if (currentWeek.value === 0) {
    currentWeek.value = 7;
  }
  const str = formatDate(currentYear.value, currentMonth.value, Now.value);

  days.value.length = 0;
  for (let i = currentWeek.value - 1; i >= 0; i -= 1) {
    const d = new Date(str);
    d.setDate(d.getDate() - i);
    days.value.push(d);
  }
  for (let i = 1; i <= 7 - currentWeek.value; i += 1) {
    const d = new Date(str);
    d.setDate(d.getDate() + i);
    days.value.push(d);
  }

  currentWeekRange.value = [
    formatDate(days.value[0].getFullYear(), days.value[0].getMonth() + 1, days.value[0].getDate()),
    formatDate(days.value[6].getFullYear(), days.value[6].getMonth() + 1, days.value[6].getDate())
  ];
  const currentDayNow = new Date();
  const currentDate = `${currentDayNow.getMonth() + 1}/${currentDayNow.getDate()}`;
  const dataArr = days.value.map((item) => `${item.getMonth() + 1}/${item.getDate()}`);
  weekGround.value = weekGround.value.map((item, index) => {
    const [dayOfWeek, ...rest] = item.split(' ');
    const lastDate = rest.pop(); // 获取最后一个日期部分
    const newRest = rest.length > 0 ? rest.join(' ') : ''; // 处理剩余部分

    const formattedDate = dataArr[index];
    const isToday = formattedDate === currentDate;
    return `${dayOfWeek} ${newRest} (${dataArr[index]})`.trim();
  });
};

const weekPre = () => {
  const d = days.value[0];
  d.setDate(d.getDate() - 7);
  updateDateAndFetchList(format(d, 'yyyy-MM-dd'));
};

const weekNext = () => {
  const d = days.value[6];
  d.setDate(d.getDate() + 7);
  updateDateAndFetchList(format(d, 'yyyy-MM-dd'));
};

// 封装初始化数据和获取课程列表的方法
const updateDateAndFetchList = (dateStr: string) => {
  // 确保 dateStr 是一个有效的日期字符串
  // if (typeof dateStr !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
  //   console.error("Invalid date string:", dateStr);
  //   return;
  // }

  const date = new Date(dateStr);
  if (isNaN(date.getTime())) {
    console.error('Invalid date:', date);
    return;
  }

  queryParams.value.testDate = dateStr;
  initData(date);
  getList();
};

const timeGround = computed(() => {
  return Array.from({ length: Math.max(...maxCoursesPerDay.value) }, (_, i) => i);
});
// const maxCoursesPerDay = course.value.map(dayCourses => dayCourses.length);
const maxCoursesPerDay = computed(() => {
  return course.value.map((dayCourses) => dayCourses.length);
});

// 获取数据
const getList = async () => {
  try {
    loading.value = true;
    const res = await listTestTeachScheduleCard(queryParams.value);
    course.value = res;
    console.log("排课数据",res);
    // testTeachScheduleList.value = res.rows;
    // total.value = res.total;
  } catch (error) {
    console.error('Failed to fetch data:', error);
    proxy?.$modal.msgError('请求数据失败，请稍后再试');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  const today = new Date();
  // queryParams.value.testDate = today.toISOString().split("T")[0];
  queryParams.value.testDate = format(today);
  initData(today);
  fetchSchoolList();
  fetchSubjectList();
  getList();
});

// //
// /** 查询教学实验排课列表 */
// const getList = async () => {
//   loading.value = true;
//   const res = await listTestTeachSchedule(queryParams.value);
//   testTeachScheduleList.value = res.rows;
//   total.value = res.total;
//   loading.value = false;
// }

const handleView = async (row?: TestTeachScheduleVO) => {
  const id = row?.testSubject || ids.value[0];
  const testDate = row?.testDate;
  const testDateEnd = row?.testDateEnd;
  router.push({ path: '/course/testTeachSchedule/testTeachTable/', query: { id: id,testDate:testDate,testDateEnd:testDateEnd } });
};
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  testTeachScheduleFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  // queryParams.value.pageNum = 1;
  // getList();
  if (queryParams.value.testDate) {
    initData(queryParams.value.testDate);
    getList();
  } else {
    const today = new Date();
    // queryParams.value.testDate = today.toISOString().split("T")[0];
    queryParams.value.testDate = format(today);
    initData(today);
    getList();
  }
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TestTeachScheduleVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  // reset();
  // dialog.visible = true;
  // dialog.title = '添加教学实验排课';
  router.push({ path: '/course/testTeachSchedule/panel/', query: { type: 0 } });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TestTeachScheduleVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getTestTeachSchedule(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改教学实验排课';
};

/** 提交按钮 */
const submitForm = () => {
  testTeachScheduleFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateTestTeachSchedule(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTestTeachSchedule(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TestTeachScheduleVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除教学实验排课编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delTestTeachSchedule(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'core/testTeachSchedule/export',
    {
      ...queryParams.value
    },
    `testTeachSchedule_${new Date().getTime()}.xlsx`
  );
};
</script>
<style lang="scss" scoped>
/* 设置表格的基本样式 */
table {
  width: 100%;
  background-color: #fff;
  // border-color: #e3e8ee;
  text-align: center;
  border-radius: 4px;
  //  border-top: 1px solid #e3e8ee;
  // border-left: 1px solid #e3e8ee;
}
tr {
  border: none;
  text-align: center;
}
td {
  // border-bottom: 1px solid #e3e8ee;
  // border-right: 1px solid #e3e8ee;
  text-align: center;
  box-sizing: border-box;
}
/* 加号图标的样式 */
.plus-icon {
  font-size: 1rem;
  cursor: pointer;
}

/* 特殊单元格的样式 */
.special-cell {
  padding-bottom: 20px;
}
td:nth-child(1) {
  width: 30px !important;
}
.time-box {
  width: 160px !important;
}
tr:nth-child(1) {
  height: 30px;
  background-color: none !important;
  border: none;
  color: #525252;
  font-weight: bold;
}

tr:first-child {
  width: 50px;
  // background: #f7f7f7;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  box-sizing: border-box;
  padding: 0 10px;
  .center {
    display: flex;
    justify-content: center;
    align-items: center;
    p {
      font-size: 20px;
      margin: 0 30px;
    }
  }
}
.course-item {
  cursor: pointer;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  background: #f0f1f3;
  border-radius: 4px;
  box-sizing: border-box;
  margin: 1px;
  height: 120px;

  p {
    color: #fff;
  }
}
.time {
  color: #707070;
  font-weight: bold;
}
</style>
